package org.go.scheduler.zk;

import java.util.concurrent.ConcurrentHashMap;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooKeeper;
import org.go.domain.GoDomain;
import org.go.domain.ScheduleTaskType;
import org.go.expcetion.GoException;
import org.go.expcetion.JobPersistenceException;
import org.go.expcetion.SchedulerException;
import org.go.log.Log;
import org.go.log.LoggerFactory;
import org.go.scheduler.AbstractScheduler;
import org.go.scheduler.SchedulerResources;
import org.go.scheduler.zk.util.ZKManager;
import org.go.threadpool.GoThreadPool;
import org.go.threadpool.GoThreadPoolRepository;
import org.go.trigger.Calendar;
import org.go.trigger.Trigger;
import org.go.trigger.TriggerKey;
import org.go.work.Work;
import org.go.work.WorkKey;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;

/**
 * 
 * @author hejie
 *
 */
public class ZkScheduler extends AbstractScheduler {
	private static final Log log = LoggerFactory.getLog(ZkScheduler.class);
	private Gson gson;
	private String PATH_BaseTaskType;
	private ZKManager zkManager;
	private SchedulerResources res;
	private GoThreadPool exe = GoThreadPoolRepository.getInstance().lookup();

	public ZkScheduler(SchedulerResources res, ZKManager zkManager) {
		this.PATH_BaseTaskType = this.zkManager.getRootPath() + "/baseTaskType";
		this.res = res;
	}

	private Work loadTaskTypeBaseInfo(String taskType) throws SchedulerException {
		Work result;
		try {
			String zkPath = this.PATH_BaseTaskType + "/" + taskType;
			if (this.getZooKeeper().exists(zkPath, false) == null) {
				return null;
			}
			String valueString = new String(this.getZooKeeper().getData(zkPath, false, null));
			result = this.gson.fromJson(valueString, Work.class);
			return result;
		} catch (JsonSyntaxException e) {
			throw new SchedulerException(e);
		} catch (KeeperException e) {
			throw new SchedulerException(e);
		} catch (InterruptedException e) {
			throw new SchedulerException(e);
		} catch (Exception e) {
			throw new SchedulerException(e);
		}
	}

	@Override
	public void addCalendar(String calName, Calendar calendar, boolean replace, boolean updateTriggers) throws SchedulerException {

	}

	@Override
	public ConcurrentHashMap<String, Object> getContext() throws SchedulerException {
		return null;
	}

	@Override
	public String getJobGroupNames() throws SchedulerException {
		return null;
	}

	@Override
	public SchedulerResources getResource() throws SchedulerException {
		return res;
	}

	@Override
	public String getSchedulerName() throws SchedulerException {
		return res.getName();
	}

	@Override
	public Trigger getTrigger(TriggerKey tKey) throws SchedulerException {
		return null;
	}

	public ZooKeeper getZooKeeper() throws Exception {
		return this.zkManager.getZooKeeper();
	}

	@Override
	public boolean isShutdown() throws SchedulerException {
		return false;
	}

	@Override
	public void notifySchedulerListenersError(String string, GoException se) throws SchedulerException {

	}

	@Override
	public void notifySchedulerListenersError(String string, JobPersistenceException se) throws SchedulerException {

	}

	@Override
	public void pauseAllWorks() throws SchedulerException {
		String zkPath = this.PATH_BaseTaskType + "/";
		Work taskType = this.loadTaskTypeBaseInfo(zkPath);
		taskType.setSts(GoDomain.STS_PAUSE);
		this.updateBaseTaskType(taskType);
	}

	public void updateBaseTaskType(Work baseTaskType) throws SchedulerException {
		try {
			if (baseTaskType.getBaseTaskType().indexOf("$") > 0) {
				throw new SchedulerException("调度任务" + baseTaskType.getBaseTaskType() + "名称不能包括特殊字符 $");
			}
			String zkPath = this.PATH_BaseTaskType + "/" + baseTaskType.getBaseTaskType();
			String valueString = this.gson.toJson(baseTaskType);
			if (getZooKeeper().exists(zkPath, false) == null) {
				getZooKeeper().create(zkPath, valueString.getBytes(), this.zkManager.getAcl(), CreateMode.PERSISTENT);
			} else {
				getZooKeeper().setData(zkPath, valueString.getBytes(), -1);
			}
		} catch (KeeperException e) {
			throw new SchedulerException(e);
		} catch (InterruptedException e) {
			throw new SchedulerException(e);
		} catch (Exception e) {
			throw new SchedulerException(e);
		} finally {

		}
	}

	/*
	 * (non-Javadoc)
	 * @see org.go.scheduler.Scheduler#pauseWork(org.go.work.WorkKey)
	 */
	@Override
	public void pauseWork(WorkKey workKey) throws SchedulerException {
		String baseTaskType = workKey.getName();
		Work taskType = loadTaskTypeBaseInfo(baseTaskType);
		taskType.setSts(ScheduleTaskType.STS_PAUSE);
		updateBaseTaskType(taskType);
	}

	@Override
	public void scheduler(Work work, Trigger trigger) throws SchedulerException {
		log.debug("Add work : {}", work.getWorkId());
		try {
			if (work.getWorkId().indexOf("$") > 0) {
				throw new SchedulerException("调度任务" + work.getWorkId() + "名称不能包括特殊字符 $");
			}
			String zkPath = this.PATH_BaseTaskType + "/" + work.getWorkId();
			if (this.getZooKeeper().exists(zkPath, false) == null) {
				String valueString = this.gson.toJson(work);
				this.getZooKeeper().create(zkPath, valueString.getBytes(), this.zkManager.getAcl(), CreateMode.PERSISTENT);
			} else {
				throw new SchedulerException("调度任务" + work.getWorkId() + "已经存在,如果确认需要重建，请先调用deleteTaskType(String baseTaskType)删除");
			}
			exe.scheduleWithCronExp(work, trigger);
		} catch (KeeperException e) {
			throw new SchedulerException(e);
		} catch (InterruptedException e) {
			throw new SchedulerException(e);
		} catch (Exception e) {
			throw new SchedulerException(e);
		}
	}

	@Override
	public void shutdown(boolean waitForWorksToComplete) throws SchedulerException {

	}

	@Override
	public void shutdownNow() throws SchedulerException {
		String goName = res.getName();
		String serverUUID = res.getUniqueIdentifier();
		//String baseTaskType = TBScheduleManager.splitBaseTaskTypeFromTaskType(taskType);
		//String zkPath = PATH_BaseTaskType + "/" + baseTaskType + "/" + goName + "/" + this.PATH_Server + "/" + serverUUID;
		String zkPath = PATH_BaseTaskType + "/" + goName + "/" + GoDomain.PATH_Server + "/" + serverUUID;
		try {
			if (this.getZooKeeper().exists(zkPath, false) != null) {
				this.getZooKeeper().delete(zkPath, -1);
			}
		} catch (KeeperException e) {
			throw new SchedulerException(e);
		} catch (InterruptedException e) {
			throw new SchedulerException(e);
		} catch (Exception e) {
			throw new SchedulerException(e);
		}
	}

	@Override
	public void unscheduleWork(TriggerKey tKey) throws SchedulerException {

	}
}
